package com.my.note.security;

import com.my.note.pojo.ResourceData;
import com.my.note.pojo.RoleData;
import com.my.note.service.UserService;
import java.util.Collection;
import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.access.SecurityConfig;
import org.springframework.security.web.FilterInvocation;
import org.springframework.security.web.access.intercept.FilterInvocationSecurityMetadataSource;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;

/**
 * @author lilun <a href="mailto:lil@chsi.com.cn">lilun</a>
 * @version $Id$ 2019年03月20 12:57
 */
@Component
public class NoteFilterInvocationSecurityMetadataSourceImpl implements FilterInvocationSecurityMetadataSource {

    private Logger logger = LoggerFactory.getLogger(this.getClass());
    AntPathMatcher antPathMatcher = new AntPathMatcher();

    @Autowired
    private UserService userService;

    @Override
    public Collection<ConfigAttribute> getAttributes(Object o) throws IllegalArgumentException {
        String requestUrl = ((FilterInvocation) o).getRequestUrl();
        List<ResourceData> resourceDataList = userService.getResourceList();
        for (ResourceData resource : resourceDataList) {
            if (antPathMatcher.match(resource.getUrl(), requestUrl)) {
                List<RoleData> roleDataList = userService.getRolesByResourceId(resource.getId());
                String[] roleArray = new String[roleDataList.size()];
                for (int i = 0; i < roleArray.length; i++) {
                    roleArray[i] = roleDataList.get(i).getRoleName();
                }
                return SecurityConfig.createList(roleArray);
            }
        }
        return SecurityConfig.createList("ROLE_USER");
    }

    @Override
    public Collection<ConfigAttribute> getAllConfigAttributes() {
        return null;
    }

    @Override
    public boolean supports(Class<?> aClass) {
        return false;
    }
}
